package com.maycurobj.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.maycur.developer.sdk.maycur.ultimate.openapi.request.budget.PostBudgetRequest;
import com.maycur.developer.sdk.maycur.ultimate.openapi.response.budget.PostBudgetResponse;
import com.maycurobj.service.http.MaycurApiService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 每刻 预算专用 接口服务
 */
@Service
@Slf4j
public class MaycurBudgetService {

    @Autowired
    private MaycurApiService maycurApiService;

    //预算查询接口
    public BigDecimal getBudget(String orgBizCode, String subjectBizCode, String strDate, int quarterNo) throws Exception {
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMdd");
        //OA日期格式化
        Date oaDate = sdf1.parse(strDate);
        try {
            PostBudgetRequest req = new PostBudgetRequest();
            req.setOrgBizCode(orgBizCode);
            req.setSubjectBizCode(subjectBizCode);
            PostBudgetResponse rsp = this.maycurApiService.getMaycurOpenApiClient().execute(req);
            log.info("预算请求返回：{}", JSONObject.toJSONString(rsp));
            List<PostBudgetResponse.Data.BudgetPlans> lists = rsp.getData().getBudgetPlans();
            List<PostBudgetResponse.Data.BudgetPlans.Budgets> budgetses = new ArrayList<>();
            int count = 0;
            for (PostBudgetResponse.Data.BudgetPlans bp : lists) {
                //特殊需求 只要季度预算
                // if ("YEARLY".equals(bp.getCompilationDimension())) {
                //    continue;
                // }
                Date mcEndDay = sdf2.parse(bp.getEndDay());
                Date mcStartDay = sdf2.parse(bp.getStartDay());
                if (bp.getEnabled() && oaDate.compareTo(mcStartDay) >= 1 && oaDate.compareTo(mcEndDay) <= 0) {
                    //可用且时间跨度符合要求
                    budgetses.addAll(bp.getBudgets());
                    count++;
                }

            }
            if (count == 1) {
                //只有一条符合要求
                List<PostBudgetResponse.Data.BudgetPlans.Budgets.BudgetUnits> budunits = budgetses.get(0).getBudgetUnits();
                for (PostBudgetResponse.Data.BudgetPlans.Budgets.BudgetUnits unit : budunits) {
                    //挑选符合要求的记录
                    if (unit.getPeriodNum() == quarterNo) {
                        log.info("获取到符合要求的预算记录:{}", JSONObject.toJSONString(unit));
                        return unit.getUsableAmount();
                    }
                }
            }

            return new BigDecimal(-1.00);
        } catch (Exception exception) {
            exception.printStackTrace();
            //钉钉报错
            return new BigDecimal(-1.00);
        }
    }

    /**
     *
     * @param amount 金额
     * @param subjectBizCode 科目
     * @param orgBizCode 主体
     * @param liuChengBianMa 流程编号
     * @return
     */
    public String setOccupyBudget(double amount,String subjectBizCode,String orgBizCode,String liuChengBianMa) {
        String url = String.format("%s%s", "https://ng.maycur.com", "/api/openapi/budget/OCCUPY");
        JSONArray reqArray = new JSONArray();
        JSONObject reqJson = new JSONObject();
        reqJson.put("uniqueCode", "OARequest-"+System.currentTimeMillis());
        reqJson.put("type", "EXTERNAL_OPENAPI"); //默认
        Map<String, Object> orgMatch = new HashMap<>();
        orgMatch.put("orgBizCode", orgBizCode);
        Map<String, Object> subjectMatch = new HashMap<>();
        subjectMatch.put("subjectBizCode", subjectBizCode);
        reqJson.put("orgMatch", orgMatch);
        reqJson.put("subjectMatch", subjectMatch);
        reqJson.put("budgetTime", System.currentTimeMillis());
        reqJson.put("amount", new BigDecimal(amount));
        reqJson.put("currency", "CNY");
        reqJson.put("reportCode", liuChengBianMa);
        reqJson.put("desc", "OA发起扣减(解除)");
        reqArray.add(reqJson);
        JSONObject tokenInfo = maycurApiService.getToken();
        try {
            log.info("请求报文:{}", JSONArray.toJSONString(reqArray));
            String ret = maycurApiService.doPostForMaycur(url, tokenInfo, JSONArray.toJSONString(reqArray));
            log.info("ret------{}", ret);
            return ret;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


}
